<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
onMounted(() => {
  const canvas = new fabric.Canvas('canvas', { width: 1200, height: 800 });
  const img1 = document.getElementById('img1');
  fabric.Image.fromURL(img1.currentSrc, img => {
    canvas.add(img);
  }, { left: 100, top: 100 });
  const img2 = document.getElementById('img2');
  fabric.Image.fromURL(img2.currentSrc, img => {
    canvas.add(img);
  }, { left: 300, top: 300 });

  // 按下鼠标事件
  canvas.on('mouse:down', function (opt) {
    const activeObject = canvas.getActiveObject(); // 获取选中的图层
    if (!activeObject) { // 如果没有选中图层的时候，可以拖动画板
      let evt = opt.e;
      this.isDragging = true
      this.lastPosX = evt.clientX // 初始化 lastPosX 和 lastPosY
      this.lastPosY = evt.clientY
    }
  })

  // 移动鼠标事件
  canvas.on('mouse:move', function (opt) {
    if (this.isDragging) {
      let e = opt.e;
      let vpt = this.viewportTransform;
      vpt[4] += e.clientX - this.lastPosX //设置 viewportTransform 的偏移
      vpt[5] += e.clientY - this.lastPosY
      this.requestRenderAll()
      this.lastPosX = e.clientX  // 更新 lastPosX 和 lastPosY
      this.lastPosY = e.clientY
    }
  })

  // 松开鼠标事件
  canvas.on('mouse:up', function (opt) {
    this.setViewportTransform(this.viewportTransform) // 更新画布的视角Viewport
    this.isDragging = false
  })
});

</script>

<template>
  <div>
    <img id="img1" src="./head.jpg" />
    <img id="img2" src="./logo.png" />
    <canvas id="canvas"></canvas>
  </div>
</template>

<style scoped>
#img1,
#img2 {
  display: none;
}
#canvas {
  margin: 10px;
  border: 1px solid #d3d3d3;
}
</style>